<?php

namespace falcon5\inc\Infrastructure\Providers;

use falcon5\inc\Base\Common;
use falcon5\inc\Base\Config;
use falcon5\inc\Infrastructure\Logger\LogJsonFormatter;
use lucatume\DI52\ServiceProvider;
use Monolog\Handler\BufferHandler;
use Monolog\Handler\RotatingFileHandler;
use Monolog\Logger;
use Monolog\Processor\UidProcessor;
use Monolog\Processor\WebProcessor;

class MonologServiceProvider extends ServiceProvider
{
    public function register()
    {
        $this->container->singleton('monolog', static function () {
            $directory = falcon5_log_dir();
            // 创建日志文件路径
            $logFile = $directory . 'falcon5.log';
            // 创建文件处理器
            $rotatingHandler = new RotatingFileHandler(
                $logFile, 
                Config::get('log.retention_days', 7), 
                Logger::DEBUG
            ); // 保留配置的天数的日志

            // 使用 BufferHandler 包装 HTTP Handler
            $fileHandler = new BufferHandler(
                $rotatingHandler, 
                Config::get('log.buffer_size', 10)
            ); // 每 N 条日志批量发送一次
            $fileHandler->setFormatter(new LogJsonFormatter());

            $sentryBufferHandler = new BufferHandler($fileHandler, 5); // 每 5 条错误日志批量发送一次

            // 创建 Monolog 实例
            $logger = new Logger(Common::PLUGIN_ID);
            // 添加唯一请求 ID
            $logger->pushProcessor(new UidProcessor());
            // 添加请求信息（如 IP、URL）
            $logger->pushProcessor(new WebProcessor());
            // 添加处理器到 Monolog
            $logger->pushHandler($fileHandler);
            $logger->pushHandler($sentryBufferHandler);
            
            return $logger;
        });
    }
}